﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.VisualBasic;
using NPOI.HSSF.Record;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Numerics;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TInventoryQueryRepository : BaseRepository<TInventory>, ITInventoryQuery
    {
        public TInventoryQueryRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }



        /// <summary>
        /// 盘点查询
        /// </summary>
        /// <param name="totalCount"></param>
        /// <param name="PalletBarcode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<TInventory> GetInventoryQuery(out int totalCount, string PalletBarcode, int pageIndex, int pageSize)
        {
            var list = Context.TInventories.AsQueryable();

            if (PalletBarcode != null)
            {
                list = list.Where(x => x.PalletBarcode == PalletBarcode);
            }
            totalCount = list.Count();

            list = list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return list.ToList();
        }

        /// <summary>
        /// 根据盘点计划ID查询盘点计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TStocktakingPlan GetTStocktakingPlanById(long id)
        {
            if (id <= 0)
            {
                return null;
            }

            var list = Context.TStocktakingPlans.FirstOrDefault(x => x.Id == id);

            return list;
        }

        /// <summary>
        /// 根据存放库位带出库区物资数量
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetInventoryNumByAreaId(int areaId)
        {

            var list = Context.TInventories.AsQueryable();

            if (areaId > 0)
            {
                var filteredList = list.Where(x => x.AreaId == areaId).ToList();
                var sumResult = filteredList.Sum(x => x.AllocateQty);
                return filteredList;
            }

            return list.ToList();
        }


        /// <summary>
        /// 存储盘点计划列表查询
        /// </summary>
        /// <param name="inventories"></param>
        /// <param name="planId"></param>
        /// <param name="planNumber"></param>
        /// <returns></returns>
        public bool GetTInventorywuliao(List<TInventorymaterialdetailsdto> pandianDanhaodto, long planId, string planNumber, out string message, out List<TLog> logs)
        {

            logs = new List<TLog>();
            using (var shiwu = Context.Database.BeginTransaction())
            {

                try
                {
                    TStocktakingPlan jihua = new TStocktakingPlan();//盘点计划表
                    if (pandianDanhaodto == null || pandianDanhaodto.Count == 0)
                    {

                        message = "数据为空，或者格式不正确";
                        shiwu.Rollback();

                        logs.Add(new TLog()
                        {
                            ActionType = 6,
                            CreateDate = DateTime.Now,
                            Description = "数据为空，或者格式不正确",
                            LogType = 1,
                        });
                        return false;
                    }
                    foreach (var item in pandianDanhaodto)
                    {
                        var contexta = Context.TStocktakingOrderDetails.Where(x => x.OrderId == planId);
                        /*   TInventorymaterialdetailsdto shuju = new TInventorymaterialdetailsdto();
                           shuju.batch = item.batch;
                           shuju.deptName = item.deptName;
                           shuju.materialNorms = item.materialNorms;
                           shuju.materialCode = item.materialCode;
                           shuju.materialName = item.materialName;
                           shuju.planId = item.planId;
                           shuju.stockCount = item.stockCount;
                           shuju.stockId = item.stockId;
                           shuju.storeLocationCode = item.storeLocationCode;
                           shuju.storeLocationRemark = item.storeLocationRemark;
                           shuju.storeName = item.storeName;
                           shuju.storeId = item.storeId;
                           shuju.storeLocationId= item.storeLocationId;

                           var kuqu = Context.TWarehouses.Find(shuju.planId);*/

                        //  TStocktakingPlan pandianjihuaid = GetTStocktakingPlanById(shuju.Id);//根据盘点计划编号查询盘点计划列表数据
                        if (!contexta.Any())
                        {
                            var contextdd = Context.TInventories.FirstOrDefault(x => x.LocationId == item.storeLocationId);
                            if (contextdd == null)
                            {
                                shiwu.Rollback();
                                message = "添加盘点单仓位编号和库存中不一致无法添加";
                                logs.Add(new TLog()
                                {
                                    ActionType = 6,
                                    CreateDate = DateTime.Now,
                                    Description = "添加盘点单仓位编号和库存中不一致无法添加",
                                    LogType = 1,
                                });


                                return false;
                            }
                            TStocktakingOrder pandiandingid = new TStocktakingOrder();//盘点单
                            pandiandingid.BatchNo = item.batch;//批次号
                            pandiandingid.MaterialName = item.materialName;//物资名称

                            pandiandingid.TouchTimes = item.storeId;//仓位id
                                                                    //  pandiandingid.OrderSn = planNumber;
                            pandiandingid.deptName = item.deptName;//归属部门名称
                            pandiandingid.materialCode = item.materialCode;//物资编码
                            pandiandingid.materialNorms = item.materialNorms;//规格型号
                            pandiandingid.WarehouseCode = item.storeName;//仓库名称
                            pandiandingid.PlanType = item.storeLocationId;
                            ///库存数量
                            pandiandingid.WarehouseId = item.stockId;//库存明细id
                            pandiandingid.WarehouseName = item.storeLocationCode;//存放库位
                            pandiandingid.storeLocationRemark = item.storeLocationRemark;//存放库位描述
                            pandiandingid.WarehouseCode = item.storeName;//仓库名称
                            pandiandingid.CellCount = Convert.ToInt32(item.stockCount);
                            pandiandingid.PriorityLevel = item.planId;//关联的盘点计划的id
                            pandiandingid.CreateDate = DateTime.Now;
                            pandiandingid.Status = 0;//创建
                            pandiandingid.planId = planId;//盘点计划id
                            pandiandingid.CreateUserId = 1;//监盘人id
                            pandiandingid.SubmitUserId = 1;//提交人id
                            pandiandingid.AuditUserName = planNumber;//盘点单号2
                                                                     // pandiandingid.OrderSn = planNumber;
                            Context.TStocktakingOrders.Add(pandiandingid);
                            Context.SaveChanges();

                        }
                        else
                        {
                            shiwu.Rollback();
                            message = "盘点单id重复数据库中已存在此编号";
                            logs.Add(new TLog()
                            {
                                ActionType = 6,
                                CreateDate = DateTime.Now,
                                Description = "盘点单id重复数据库中已存在此编号",
                                LogType = 1,
                            });

                            return false;
                        }

                        /*    return true;
                                 if (Context.SaveChanges() <= 0)
                                 {
                                     shiwu.Rollback();
                                     return false;
                                 }   */

                    }
                    var pandaidan = Context.TStocktakingOrderDetails.FirstOrDefault(x => x.OrderSn == planNumber);
                    if (pandaidan == null)
                    {
                        TStocktakingOrderDetail stockingorder = new TStocktakingOrderDetail();//盘点明细单

                        stockingorder.OrderId = Convert.ToInt32(planId);
                        stockingorder.OrderSn = planNumber;//默认创建状态是创建
                        /*stockingorder.BatchNo = shuju.batch;//批次号
                        stockingorder.InventoryId = shuju.stockId;//库存明细id
                        stockingorder.MaterialCode = shuju.materialCode;//物资编码
                        stockingorder.MaterialName = shuju.materialName;//物资名称
                        stockingorder.OrderSn = planNumber;//盘点计划里盘点单号
                        stockingorder.CellId = shuju.storeId;//仓位
                        stockingorder.CreateDate = DateTime.Now;
                        stockingorder.SupplierName = shuju.storeName;//仓库名称
                        stockingorder.WarehouseId = 1;//提交人id*/
                        Context.TStocktakingOrderDetails.Add(stockingorder);
                        //TInventory kucun = new TInventory();//库存表 
                        //kucun.LogicalPartCode = shuju.storeId;
                        //kucun.LocationCode = shuju.storeLocationId;
                        //Context.TInventory.Add(kucun);
                        if (logs.Count <= 0)
                        {
                            Context.SaveChanges();
                            shiwu.Commit();
                            message = "添加成功";
                            return true;
                        }
                        else
                        {
                            message = "添加失败";
                            shiwu.Rollback();
                            return true;
                        }
                    }
                    else
                    {
                        shiwu.Rollback();
                        logs.Add(new TLog()
                        {
                            ActionType = 6,
                            CreateDate = DateTime.Now,
                            Description = "盘点单号已存在",
                            LogType = 1,
                        });
                        message = "盘点单号已存在";
                        return false;

                    }
                    return true;
                }
                catch (Exception ex)
                {
                    shiwu.Rollback();

                    message = ex.Message;
                    logs.Add(new TLog()
                    {
                        ActionType = 6,
                        CreateDate = DateTime.Now,
                        Description = "catch:" + ex.Message,
                        LogType = 1,
                    });
                    return false;
                }

            }

            //库存明细查询





        }
        /// <summary>
        /// 修改盘点单状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>

        public bool UpdatePandianlist(int chuanbianhao)
        {
            using (var shiwu = Context.Database.BeginTransaction())
            {
                try
                {
                    var xiuggai = Context.TStocktakingOrders.Find(chuanbianhao);
                    TStocktakingOrder stocktakingOrder = new TStocktakingOrder();
                    stocktakingOrder.OrderSn = xiuggai.OrderSn;
                    stocktakingOrder.CreateUserId = xiuggai.CreateUserId;//监盘人id
                    TStocktakingOrderDetail liebiao = new TStocktakingOrderDetail();
                    liebiao.WarehouseId = xiuggai.WarehouseId;
                    Context.SaveChanges();
                    if (Context.SaveChanges() < 0)
                    {
                        shiwu.Rollback();
                        return false;
                    }
                    Context.TStocktakingOrders.Update(stocktakingOrder);
                    shiwu.Commit();
                    return true;
                }
                catch (Exception)
                {
                    shiwu.Rollback();
                    return false;
                    throw new Exception();
                }
            }

        }


        public bool Getpandianxiugai(string ordernum, out string message)
        {

            using (var reader = Context.Database.BeginTransaction())
            {
                try
                {
                    var robj = Context.TStocktakingOrderDetails.FirstOrDefault(x => x.OrderSn == ordernum);

                    if (robj != null)
                    {
                        robj.Status = 2;
                        var uobj = Context.TStocktakingOrders.Where(x => x.planId == robj.OrderId && x.Status == 1);
                        if (uobj != null)
                        {
                            foreach (var item in uobj)
                            {
                                item.Status = 2;

                                Context.TStocktakingOrders.Update(item);

                                //var jihua = Context.TStocktakingOrders.Where(x => x.MaterialName == item.materialName && x.PlanType == item.storeLocationId && x.planId == planid).FirstOrDefault();
                            }
                            robj.ExpectedStationIds = "已执行";
                            Context.TStocktakingOrderDetails.Update(robj);
                            Context.SaveChanges();
                            message = "已回传";
                            reader.Commit();
                            return true;
                        }
                        message = "未回传";
                        return false;
                    }
                    message = "盘点单号和数据库里不一致,";
                    return false;
                }
                catch (Exception ex)
                {

                    throw new Exception(ex.Message);
                }
            }
        }
        public bool UpdatePandianlist(TInventorymaterialdetailsdto dto)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// pda上显示的数据
        /// </summary>
        /// <returns></returns>
        public object GetPdaxianshishuju(int? planid, int pageindex, int pagesize, out int totalCount)
        {
            TStocktakingOrderDetail aca = new TStocktakingOrderDetail();

            var alist = Context.TStocktakingOrders.AsQueryable();//盘点计划
            var blist = Context.TStocktakingOrderDetails.AsQueryable();//盘点单
            var clist = Context.TInventories.AsQueryable();//库存表
            var dlist = Context.TWarehouses.AsQueryable();//库房
            if (planid != null)
            {
                blist.Where(x => x.OrderId == planid);
            }
            var query = from a in blist
                        where a.Status == 0


                        //join c in clist
                        // on b.CellId equals c.LocationId
                        orderby a.CreateDate descending
                        select new
                        {


                            items = alist.Where(n => n.planId == a.OrderId).Select(n => new
                            {
                                batch = n.BatchNo,
                                deptename = n.deptName,
                                materialCode = n.materialCode,
                                materialName = n.MaterialName,
                                materialNorms = n.materialNorms,
                                planId = n.planId,
                                storeId = n.TouchTimes,
                                stockId = n.WarehouseId,
                                stockCount = n.CellCount,
                                storeLocationCode = n.WarehouseName,
                                storeLocationRemark = n.storeLocationRemark,
                                storeName = n.WarehouseCode,
                                storeLocationId = n.PlanType,
                                ParentPalletBarcode = clist.FirstOrDefault(x => x.LocationId == Convert.ToInt32(n.PlanType) && x.MaterialName == n.MaterialName).ParentPalletBarcode
                                // LocationCode= c.LocationCode,
                                // LocationId=c.LocationId
                            }).ToList(),
                            planId = a.OrderId,
                            planNumber = a.OrderSn
                        };
            totalCount = query.Count();
            return query.Where(x => x.planId == x.planId);
        }
    }

}

